package best.driver.android.Activity.Order;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.*;
import best.driver.android.Activity.Base.BaseActivity;
import best.driver.android.AppInfo;
import best.driver.android.Beans.NewOrderInfo;
import best.driver.android.Beans.OrderDetailInfo;
import best.driver.android.Beans.PushType;
import best.driver.android.BestApp;
import best.driver.android.Event.HideMultiAddressEvent;
import best.driver.android.Event.NewOrderAcceptedEvent;
import best.driver.android.Map.LatLng;
import best.driver.android.NetBase.BackService;
import best.driver.android.R;
import best.driver.android.RequestFactory;
import best.driver.android.Utils.VoiceUtils;
import best.driver.android.View.NewOrderView;
import best.driver.android.common.app.AppProxyFactory;
import best.driver.android.common.network.ApiRequest;
import best.driver.android.common.network.ApiStringRequest;
import best.driver.android.common.network.BestApiError;
import best.driver.android.common.network.BestError;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

import java.util.Timer;
import java.util.TimerTask;

public class AcceptOrderActivity extends BaseActivity{

    private NewOrderInfo mNewOrder;

    private byte mStatus;

    private boolean mIsFromOrderList = false;

    private Timer timer;
    private TimerTask timerTask;
    private int waitingSeconds = 90;

    @InjectView(R.id.new_order_view)
    NewOrderView mNewOrderView;

    @InjectView(R.id.tv_order_status)
    TextView mTvOrderStatus;

    @InjectView(R.id.tv_accept_order_hint)
    TextView mTvAcceptOrderHint;

    @InjectView(R.id.tv_accept_order_status)
    TextView mTvAcceptOrderStatus;

    @InjectView(R.id.tv_remain_time)
    TextView mTvRemainTime;

    @InjectView(R.id.btn_accept_order)
    Button mBtnAcceptOrder;

    @InjectView(R.id.ll_accept_order_result)
    LinearLayout mLinearResult;

    @InjectView(R.id.ll_order_accept_failed)
    LinearLayout mLinearAcceptFailed;

    @InjectView(R.id.tv_accept_by_others)
    TextView mTvFailed;

    @InjectView(R.id.tv_order_accept_succeed)
    TextView mTvAcceptSuccess;

    @InjectView(R.id.iv_accept_status_img)
    ImageView mIvAcceptStatusImg;

    @InjectView(R.id.btn_ignore_order)
    Button mBtnIgnoreOrder;

    @OnClick(R.id.btn_ignore_order)
    protected void ignoreOrder() {
        if(mNewOrder != null) {
            ApiStringRequest request = RequestFactory.createIgnoreOrder(mNewOrder.orderId);
            showWaiting();
            request.setListener(new ApiRequest.ApiRequestListener<String>() {
                @Override
                public void onRequestSuccess(String response) {
                    hideWaiting();
                    AcceptOrderActivity.this.finish();
                }

                @Override
                public void onRequestError(BestError error) {
                    hideWaiting();
                }
            });
            AppProxyFactory.getProxy().getNetworkManager().enqueueRequest(request);
        }
    }

    @OnClick(R.id.btn_continue_order)
    protected void continueOrder() {
        AcceptOrderActivity.this.finish();
    }

    @OnClick(R.id.btn_accept_order)
    protected void receiveOrder() {
        if("已抢单".equals(mTvAcceptOrderStatus.getText().toString().trim())) {
            return;
        }
        if(mNewOrder != null && !TextUtils.isEmpty(mNewOrder.orderId)) {
            mBtnAcceptOrder.setEnabled(false);
            ApiStringRequest request = RequestFactory.createReceiveOrderRequest(mNewOrder.orderId, String.valueOf(mNewOrder.driverDistance));
            request.setListener(new ApiRequest.ApiRequestListener<String>() {
                @Override
                public void onRequestSuccess(String response) {
                    mBtnAcceptOrder.setEnabled(true);
                    mTvAcceptOrderStatus.setText("已抢单");
                    mTvAcceptOrderStatus.setTextColor(getResources().getColor(R.color.c666));
                    mTvRemainTime.setVisibility(View.GONE);
                    mTvAcceptOrderHint.setVisibility(View.VISIBLE);
                    mBtnIgnoreOrder.setVisibility(View.GONE);
                    AppInfo.showToast(AcceptOrderActivity.this, "已抢单");
                    stopTimer();
                }

                @Override
                public void onRequestError(BestError error) {
                    mBtnAcceptOrder.setEnabled(true);
                    if(error instanceof  BestApiError) {
                        mTvAcceptOrderStatus.setText("抢单失败");
                        mTvAcceptOrderStatus.setTextColor(getResources().getColor(R.color.c666));
                        mTvRemainTime.setVisibility(View.GONE);
                        stopTimer();
                        mBtnAcceptOrder.setEnabled(false);
                        AppInfo.showToast(AcceptOrderActivity.this, ((BestApiError) error).getErrorMessage());
                    }
                }
            });
            AppProxyFactory.getProxy().getNetworkManager().enqueueRequest(request);
        } else {
            Intent intent = new Intent();
            intent.setAction(BackService.MESSAGE_ACTION);
            sendBroadcast(intent);
            return;
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setView(R.layout.activity_accept_order_bak);
        ButterKnife.inject(this, view);
        Intent args = getIntent();
        mNewOrder = (NewOrderInfo) args.getSerializableExtra("new_order");
        mStatus = args.getByteExtra("status", (byte) 0);
        mIsFromOrderList = args.getBooleanExtra("fromOrderList", false);
        showOrderNew(mNewOrder, mStatus);
        EventBus.getDefault().register(this);
        hideTopBar();
    }

    public void showOrderNew(NewOrderInfo orderInfo, byte status) {
        if(orderInfo != null) {
            mNewOrder = orderInfo;
        }
        if(status == PushType.NEW_ORDER) {
            mTvAcceptOrderStatus.setText("抢单");
            mTvAcceptOrderStatus.setTextColor(getResources().getColor(R.color.white));
            mTvRemainTime.setVisibility(View.VISIBLE);
            showNewOrderCome(orderInfo);
            //mNewOrderView.setPrice(orderInfo.estimatePrice);
            mNewOrderView.setNewOrderView(orderInfo);
            mBtnAcceptOrder.setEnabled(true);
            waitingSeconds = 90;
            startTimer(waitingSeconds);
        } else if(status == PushType.NEW_ORDER_ACCEPTED) {
            mBtnAcceptOrder.setEnabled(false);
            showOrderAcceptSuccess(orderInfo);
            mTvAcceptOrderHint.setVisibility(View.GONE);
        } else if(status == PushType.NEW_ORDER_FAILED) {
            showOrderAcceptFailed(orderInfo.orderId);
            mTvAcceptOrderHint.setVisibility(View.GONE);
            mBtnAcceptOrder.setEnabled(false);
        }
        if (mNewOrder != null) {

        }
    }

    public void showOrderNew(OrderDetailInfo orderInfo, byte status) {
        if(mNewOrder == null) {
            mNewOrder = new NewOrderInfo(orderInfo);
        }
        if(status == PushType.NEW_ORDER) {
            mTvAcceptOrderStatus.setText("抢单");
            mTvAcceptOrderStatus.setTextColor(getResources().getColor(R.color.white));
            mTvRemainTime.setVisibility(View.VISIBLE);
            mIsFromOrderList = false;
            showNewOrderCome(null);
            mBtnAcceptOrder.setEnabled(true);
            waitingSeconds = 90;
            startTimer(waitingSeconds);
        } else if(status == PushType.NEW_ORDER_ACCEPTED) {
            showOrderAcceptSuccess(orderInfo);
            mTvAcceptOrderHint.setVisibility(View.GONE);
        } else if(status == PushType.NEW_ORDER_FAILED) {
            showOrderAcceptFailed(null);
            mTvAcceptOrderHint.setVisibility(View.GONE);
        }
        if (mNewOrder != null) {

        }
    }

    public void onEventMainThread(NewOrderAcceptedEvent event) {
        if(mNewOrder != null && event.orderId.equals(mNewOrder.orderId)) {
            showOrderAccepted();
        }
    }

    public void onEventMainThread(HideMultiAddressEvent event) {
        if(!TextUtils.isEmpty(event.flag)) {
            mNewOrderView.hideListView(event.flag);
        }
    }

    private void showOrderAccepted() {

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void showNewOrderCome(NewOrderInfo orderInfo) {
        if(!mIsFromOrderList) {
            VoiceUtils.playBadNetworkAlarm(false);
        }
        mLinearResult.setVisibility(View.GONE);
        mTvAcceptOrderHint.setVisibility(View.GONE);
        mBtnIgnoreOrder.setVisibility(View.VISIBLE);
        mIvAcceptStatusImg.setImageResource(R.drawable.icon_complete);
    }

    public void showOrderAcceptSuccess(final NewOrderInfo orderInfo) {
        mLinearResult.setVisibility(View.VISIBLE);
        mTvAcceptSuccess.setVisibility(View.VISIBLE);
        mLinearAcceptFailed.setVisibility(View.GONE);
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent(AcceptOrderActivity.this, OrderOperationActivity.class);
                intent.putExtra("orderId", orderInfo.orderId);
                startActivity(intent);
                AcceptOrderActivity.this.finish();
            }
        }, 1000);
    }

    public void showOrderAcceptSuccess(final OrderDetailInfo orderInfo) {
        mLinearResult.setVisibility(View.VISIBLE);
        mTvAcceptSuccess.setVisibility(View.VISIBLE);
        mLinearAcceptFailed.setVisibility(View.GONE);
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent(AcceptOrderActivity.this, OrderOperationActivity.class);
                intent.putExtra("orderId", orderInfo.orderId);
                startActivity(intent);
                AcceptOrderActivity.this.finish();
            }
        }, 1000);
    }

    public void showOrderAcceptFailed(String orderId) {
        if(!TextUtils.isEmpty(orderId) && orderId.equals(mNewOrder.orderId)) {
            mLinearResult.setVisibility(View.VISIBLE);
            mTvAcceptSuccess.setVisibility(View.GONE);
            mLinearAcceptFailed.setVisibility(View.VISIBLE);
            mTvOrderStatus.setText("已被抢");
            mIvAcceptStatusImg.setImageResource(R.drawable.icon_cry);
        }
    }

    public void showOrderAcceptCanceled(String orderId) {
        if(!TextUtils.isEmpty(orderId) && orderId.equals(mNewOrder.orderId)) {
            mLinearResult.setVisibility(View.VISIBLE);
            mTvAcceptSuccess.setVisibility(View.GONE);
            mTvFailed.setText("订单已取消");
            mLinearAcceptFailed.setVisibility(View.VISIBLE);
            mTvOrderStatus.setText("已取消");
            mIvAcceptStatusImg.setImageResource(R.drawable.icon_cry);
        }
    }

    private void updateByTimer() {
        Activity activity = getActivity();
        if(activity != null) {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mTvRemainTime.setText(String.valueOf(waitingSeconds));
                    if (waitingSeconds == 0) {
                        AcceptOrderActivity.this.finish();
                    } else {
                        waitingSeconds--;
                        startTimer(1000);
                    }
                }
            });
        }
    }


    private void stopTimer() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }
    }

    private void startTimer(int delay) {
        mTvRemainTime.setText(String.valueOf(waitingSeconds));
        stopTimer();
        timer = new Timer("GET_VERIFYCODE");
        timerTask = new TimerTask() {
            @Override
            public void run() {
                updateByTimer();
            }
        };
        timer.schedule(timerTask, delay);
    }



}
